package cn.tedu.boot61.controller;

import cn.tedu.boot61.mapper.WeiboMapper;
import cn.tedu.boot61.vo.User;
import cn.tedu.boot61.vo.Weibo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class WeiboController {
    @Autowired(required = false)
    WeiboMapper mapper;

    @RequestMapping("/weibo/insert")
    public int insert(Weibo weibo, MultipartFile picFile,HttpSession session) throws IOException {
        //得到当前登录用户的对象
        User u = (User) session.getAttribute("u");
        if (u==null){//代表为登录
            return 2;//发布失败,  请先登录
        }
        //得到原始文件民
        String fileName = picFile.getOriginalFilename();
        //得到后缀名
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //
        fileName = UUID.randomUUID()+suffix;
        //文件夹路径
        String dirPath = "f:/upload/";
        File dirFile = new File(dirPath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        String filePath = dirPath+fileName;
        picFile.transferTo(new File(filePath));

        //author,url,created,user_id
        weibo.setAuthor(u.getNick());
        weibo.setUrl("/"+fileName);
        weibo.setCreated(new Date());//new Date得到的是当前系统时间
        weibo.setUserId(u.getId());//把当前登录的用户id保存
        mapper.insert(weibo);


        return 1;//发布成功
    }

    @RequestMapping("/weibo/select")
    public List<Weibo> select(){
        return mapper.select();
    }

    @RequestMapping("/weibo/selectMyself")
    public List<Weibo> selectMyself(HttpSession session){
        User u = (User) session.getAttribute("u");
        if (u==null){//重启项目的时候,session缓存会被清除报null
            return new ArrayList<>();//空数组
        }
        //通过当前登录用户的id查所有的微博
        return mapper.selectByUserId(u.getId());
    }

    @RequestMapping("/weibo/delete")
    public void delete(int id){
        mapper.delete(id);
    }

    @RequestMapping("/weibo/selectById")
    public Weibo selectById(int id){
        return mapper.selectById(id);
    }

}
